// 初始搜索时间范围
export const getSearchTimes = (val: any) => {
  // 创建一个新的日期对象
  const date = new Date(val);

  // 获取日期的各个部分
  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate();

  const createAtBegin = new Date(
    new Date(Y, M - 1, 1).setHours(0, 0, 0)
  ).toISOString(); //默认开始时间
  const createAtEnd = new Date(
    new Date(Y, M - 1, D).setHours(23, 59, 59)
  ).toISOString(); //默认结束时间
  // console.log(createAtBegin, createAtEnd);
  return [createAtBegin, createAtEnd];
};

// 快捷时间筛选
export const getShortCuts = () => {
  const shortcuts = [
    {
      text: "最近一周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        new Date(start.setHours(0, 0, 0)).toISOString();
        new Date(end.setHours(23, 59, 59)).toISOString();
        return [start, end];
      },
    },
    {
      text: "最近一个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        new Date(start.setHours(0, 0, 0)).toISOString();
        new Date(end.setHours(23, 59, 59)).toISOString();
        return [start, end];
      },
    },
    {
      text: "最近三个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        new Date(start.setHours(0, 0, 0)).toISOString();
        new Date(end.setHours(23, 59, 59)).toISOString();
        return [start, end];
      },
    },
  ];
  return shortcuts;
};

// 时间格式化方法
export const formatDate = (cellValue: string) => {
  // cellValue 可能是 ISO 格式的时间字符串
  if (cellValue) {
    const date = new Date(cellValue);
    if (
      "1/1/1 08:05:43" ==
      date.toLocaleDateString("zh-CN") + " " + date.toLocaleTimeString("zh-CN")
    ) {
      return null;
    }
    return date.toLocaleDateString("zh-CN");
  }
  return null;
};

// 日期格式化方法
export const tableTimeDate = (val: string) => {
  if (val == "0001-01-01T00:00:00Z" || val == null) {
    return null;
  } else {
    // 创建一个新的日期对象
    const date = new Date(val);

    // 获取日期的各个部分
    const Y = date.getFullYear().toString().padStart(4, "0");
    const M = (date.getMonth() + 1).toString().padStart(2, "0");
    const D = date.getDate().toString().padStart(2, "0");

    // 获取时间的各个部分
    /*  const h = (date.getHours()).toString().padStart(2,"0");
    const m = (date.getMinutes()).toString().padStart(2,"0");
    const s = (date.getSeconds()).toString().padStart(2,"0"); */

    // const timeDate = `${Y}/${M}/${D}/ ${h}:${m}:${s}`;
    const timeDate = `${Y}/${M}/${D}`;
    return timeDate;
  }
};
// 时间格式化方法
export const tableTimeDateMsg = (val: string) => {
  if (val == "0001-01-01T00:00:00Z" || val == null) {
    return null;
  } else {
    // 创建一个新的日期对象
    const date = new Date(val);

    // 获取日期的各个部分
    const Y = date.getFullYear().toString().padStart(4, "0");
    const M = (date.getMonth() + 1).toString().padStart(2, "0");
    const D = date.getDate().toString().padStart(2, "0");

    // 获取时间的各个部分
    const h = date.getHours().toString().padStart(2, "0");
    const m = date.getMinutes().toString().padStart(2, "0");
    const s = date.getSeconds().toString().padStart(2, "0");

    const time = `${Y}/${M}/${D}/ ${h}:${m}:${s}`;
    return time;
  }
};

// 时间格式化方法
export const tableTimeDateMsgTow = (val: string) => {
  if (val == "0001-01-01T00:00:00Z" || val == null) {
    return null;
  } else {
    // 创建一个新的日期对象
    const date = new Date(val);

    // 获取日期的各个部分
    const Y = date.getFullYear().toString().padStart(4, "0");
    const M = (date.getMonth() + 1).toString().padStart(2, "0");
    const D = date.getDate().toString().padStart(2, "0");

    // 获取时间的各个部分
    const h = date.getHours().toString().padStart(2, "0");
    const m = date.getMinutes().toString().padStart(2, "0");
    const s = date.getSeconds().toString().padStart(2, "0");

    const time = `${Y}-${M}-${D}T${h}:${m}:${s}+08:00`;
    return time;
  }
};

// 去除HTML数据中的空行
export const removeEmptyLines = (val: string) => {
  const regex = /<p[^>]*><\/p>|<br\s*\/?>/g;
  return val.replace(regex, "");
};

// "Enter"事件的方法
export const addEnterEvent = (inputId:any, callback:any) => {
  var input = document.getElementById(inputId);
  if(input) {
    input.addEventListener('keypress', function(event) {
      if(event.key === 'Enter' || event.keyCode === 13) {
        callback();
      }
    })
  } else {
    console.log('Global Enter key was pressed');
  }
};

// 验证输入框中的字符串是否为空
export const isValidateString = (data: string) => {
  console.log("字符串内容：", data);
  if (data.trim() === '') {
    // 校验不通过
    return true;
  } else {
    // 校验通过
    return false;
  }
};

// 验证富文本编辑器内容是否为空格或空行
export const isValidateEditor = (msg: any) => {
  console.log("校验富文本内容：", msg);
  const isImgTag = /<img[^>]*>/i.test(msg);
  if(isImgTag) {
    return false;
  } else {
    // 移除所有 HTML 标签
    const noTagsMsg = msg.replace(/<[^>]*>/g, '');
  
    // 检查是否只包含空行或空格
    const lines = noTagsMsg.split('&nbsp;');
    return lines.every((line: any) => line.trim() === '' || line.trim() === ' ');
  }
};

// 【我负责的任务】中当前用户区分测试true和研发false
export const isUserAuthId = (val: any) => {
  console.log("当前用户权限：", val);
  if (val == '111' || val == '666') {
    return true;
  } else if (val == '555' || val == '777' || val == '999') {
    return false;
  }
}

// 各需求/任务状态数据
export const fatherStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "待分配",
        bgColor: "#9FA535",
        operate: "分配",
      };
    case 2:
      return {
        status: 2,
        text: "待开发",
        bgColor: "#763838",
        operate: "开发"
      };
    case 3:
      return {
        status: 3,
        text: "开发中",
        bgColor: "#9FA535",
        operate: "提测"
      };
    case 4:
      return {
        status: 4,
        text: "详细设计确认中",
        bgColor: "#386E76",
        operate: "审核"
      };
    case 5:
      return {
        status: 5,
        text: "测试中",
        bgColor: "#387664",
        operate: "是否通过"
      };
    case 6:
      return {
        status: 6,
        text: "待上线评审",
        bgColor: "#5F9EA0",
        operate: "分配"
      };
    case 7:
      return {
        status: 7,
        text: "待上线",
        bgColor: "#1E90FF",
        operate: "上线结果"
      };
    case 8:
      return {
        status: 8,
        text: "已上线",
        bgColor: "#1E90FF",
        operate: "评分"
      };
    case 9:
      return {
        status: 9,
        text: "已关闭",
        bgColor: "#424242",
        operate: "撤回"
      };
    default:
      return {
        status: 9,
        text: "已关闭",
        bgColor: "#424242",
      };
  }
};


// 各需求审核状态数据
export const enterStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "待审核",
        bgColor: "#F56C6C",
        content: "待审核",
        operate1: "催他"
      };
    case 2:
      return {
        status: 2,
        text: "未通过",
        bgColor: "#E6A23C",
        content: "未通过",
        operate1:"审核记录"
      };
    case 3:
      return {
        status: 3,
        text: "已通过",
        bgColor: "#67C23A",
        content: "已通过",
        operate1: "选择技术负责人"
      };
    default:
      return {
        status: 1,
        text: "待审核",
        bgColor: "#DF0101",
        content: "待审核",
        operate1: "催他"
      };
  }
};

// 测试状态
export const testStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "未生效",
        bgColor: "#909399",
      };
    case 2:
      return {
        status: 2,
        text: "待测试",
        bgColor: "#9FA535",
      };
    case 3:
      return {
        status: 3,
        text: "测试中",
        bgColor: "#9FA535",
      };
    case 4:
      return {
        status: 4,
        text: "测试通过",
        bgColor: "#67C23A",
      };
    case 5:
      return {
        status: 5,
        text: "测试未通过",
        bgColor: "#909399",
      };
    default: 
      return {
        status: val,
        text: "未生效",
        bgColor: "#909399",
      }
  }
};

// 上线参与类型
export const bearStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "研发",
      };
    case 2:
      return {
        status: 2,
        text: "运维",
      };
    case 3:
      return {
        status: 3,
        text: "测试",
      };
  }
};


// 处理文件地址
export const handleFileName = (val: string) => {
  // console.log("文件地址：", val);
  const lastIndex = val.lastIndexOf('_');

  if(lastIndex !== -1) {
      return {
          url: val,
          type: val.split(".").pop() || 'txt',
          name: val.substring(lastIndex + 1)
      }
  } else {
    return {
          url: val,
          type: val.split(".").pop() || 'txt',
          name: `未知.${val.split('.').pop()}`
      }
  }
};

// 下载文件方法
export const handleDownloadFile = async (val: any, baseUrl: string) => {
  try {
    const fullUrl = `${baseUrl}${val.url}`;


    // 检查响应状态码
    const response = await fetch(fullUrl, { method: 'HEAD' });
    if (!response.ok) {
      throw new Error(`服务器返回错误状态码：${response.status}`);
    }
   /*  const fullUrl = `${baseUrl}${val.url}`;


    // 检查响应状态码
    const response = await fetch(fullUrl, { method: 'GET' });
    if (!response.ok) {
      throw new Error(`服务器返回错误状态码：${response.status}`);
    } */


    const link = document.createElement('a');
    console.log("当前下载文件：", val);
    link.href = `${baseUrl}${val.url}`;


    const lastIndex = val.url.lastIndexOf('_');//找到最后一个“_”的位置
    let fileName: string;

    if (lastIndex !== -1) {
      fileName = val.url.substring(lastIndex + 1);//截取“_”后面的所有字符串
    } else {
      const fileType = val.type || 'txt';
      fileName = `未知.${fileType}`
    };

    link.download = decodeURIComponent(fileName);//用于设置下载文件的文件名

    // link.download = `${index+1}.${val.type}`;

    console.log("下载文件名：", link.download);

    // 添加错误处理
    link.onerror = async (error) => {
      console.log(error);
      alert("文件未找到，请检查链接的合法性。");
      return;
    };

    document.body.appendChild(link);
    console.log(link);
    link.click();
    document.body.removeChild(link);
    // URL.revokeObjectURL(val.url);

  } catch (error) {
      console.log("下载文件失败：", error);
      alert("下载文件失败，请检查链接的合法性和网络连接。");
      return;
  }
};